<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Bell, Close } from '@element-plus/icons-vue'
import { websocketService } from '@/utils/websocket'

// 从WebSocket服务获取消息列表
const messages = websocketService.messages
// 连接状态
const connected = websocketService.connected
// 新消息标志
const hasNewMessage = websocketService.hasNewMessage

// 控制通知栏显示
const showNotification = ref(false)
// 当前显示的消息
const currentMessage = ref('')

// 监听新消息标志
watch(() => hasNewMessage.value, (newValue) => {
  if (newValue) {
    // 有新消息时显示通知
    currentMessage.value = messages.value[0].content
    showNotification.value = true

    // 重置新消息标志
    websocketService.resetNewMessageFlag()

    // 3秒后自动隐藏
    setTimeout(() => {
      showNotification.value = false
    }, 3000)
  }
})

// 关闭通知
const closeNotification = () => {
  showNotification.value = false
}
</script>

<template>
  <transition name="notification-fade">
    <div v-if="showNotification" class="websocket-notification">
      <div class="notification-content">
        <span class="notification-icon">
          <el-icon><Bell /></el-icon>
        </span>
        <span class="notification-message">{{ currentMessage }}</span>
        <span class="notification-close" @click="closeNotification">
          <el-icon><Close /></el-icon>
        </span>
      </div>
    </div>
  </transition>
</template>

<style scoped>
.websocket-notification {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 9999;
  width: auto;
  max-width: 80%;
}

.notification-content {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-left: 4px solid #409EFF;
}

.notification-icon {
  margin-right: 10px;
  color: #409EFF;
}

.notification-message {
  flex: 1;
  font-size: 14px;
  color: #333;
}

.notification-close {
  margin-left: 16px;
  cursor: pointer;
  color: #909399;
}

.notification-close:hover {
  color: #606266;
}

.notification-fade-enter-active,
.notification-fade-leave-active {
  transition: all 0.3s;
}

.notification-fade-enter-from,
.notification-fade-leave-to {
  opacity: 0;
  transform: translate(-50%, -20px);
}
</style>
